package com.eh.erd.sms.controller.api;

import com.eh.common.exception.Assert;
import com.eh.common.result.R;
import com.eh.common.result.ResponseEnum;
import com.eh.common.util.RandomUtils;
import com.eh.common.util.RegexValidateUtils;
import com.eh.erd.sms.feign.CoreUserInfoFeign;
import com.eh.erd.sms.service.SmsService;
import com.eh.erd.sms.util.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuyuanwei
 * @version 1.0
 * @date 2021/5/12 10:21
 */

@RestController
@Slf4j
@RequestMapping("/api/sms")
@Api(tags = "短信发送平台管理")
public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CoreUserInfoFeign coreUserInfoFeign;

    @ApiOperation("短信验证码")
    @GetMapping("/send/{mobile}")
    public R send(@ApiParam("手机号") @PathVariable String mobile){


        Boolean checkMobile = coreUserInfoFeign.checkMobile(mobile);
        Assert.isTrue(checkMobile==false,ResponseEnum.MOBILE_EXIST_ERROR);
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);
        Map<String,Object> map=new HashMap<>();
        String fourBitRandom = RandomUtils.getFourBitRandom();
        map.put("code", fourBitRandom);
        smsService.send(mobile, SmsProperties.TEMPLATE_CODE,map);

        redisTemplate.opsForValue().set("erd:sms:code:"+mobile,fourBitRandom,5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }

}
